package com.its.util.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 28691
 */
//@Component
//@Order(-1) //Spring执行优先级设置，越小越先执行
public class GatewayFilter implements GlobalFilter {

    /**
     * 执行过滤逻辑
     * @param exchange 封装了当前请求和响应的上下文对象
     * @param chain 过滤器链
     * @return Mono<Void>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、获取所有的headers参数
        MultiValueMap<String,String> headers = exchange.getRequest().getHeaders();

        // 2、获取指定的headers参数
        String token = headers.getFirst("token");

        // 3、校验参数值
        if ("I am so handsome.".equals(token)) {
            // 3-1 如果参数值正确，则放行请求，继续执行后续过滤器
            return chain.filter(exchange);
        } else {
            // 4、拦截请求，返回403状态码
            // 4-1 设置状态码
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            // 4-2 结束请求处理
            return exchange.getResponse().setComplete();
        }
    }
}
